package com.qys.livesMall.event.listener;

import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.utils.SpringUtils;
import com.qys.livesMall.shop.enums.ShopEventTypeEnum;
import com.qys.livesMall.shop.event.ShopEvent;
import com.qys.livesMall.shop.event.handle.BaseHandler;
import com.qys.livesMall.shop.modal.entity.ShopEventInfo;
import com.qys.livesMall.shop.service.ShopEventInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

@Slf4j
@RequiredArgsConstructor
public class ShopEventListener {

    @Async
    @Order
    @EventListener(ShopEvent.class)
    public void eventExc(ShopEvent event) {
        ShopEventInfo dto = (ShopEventInfo) event.getSource();
        try {
            BaseHandler handler= (BaseHandler) SpringUtils.getBean(ShopEventTypeEnum.getByType(dto.getEventType()).getEvent());
            handler.handle(dto);
        }catch (Exception e){
            dto.setStatus(Constants.YesNoInt.NO);
            dto.setReCount(dto.getReCount()+1);
            ShopEventInfoService shopEventInfoService=SpringUtils.getBean(ShopEventInfoService.class);
            dto.setErrorLog("错误："+e);
            shopEventInfoService.save(dto);
            log.error("错误："+e);
        }
    }
}
